package com.zhaogang.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zhaogang.entity.SaleAccount;
import com.zhaogang.entity.UserAccount;
import com.zhaogang.service.SaleAccountService;
import com.zhaogang.service.UserAccountService;

@Controller
@RequestMapping("/saleAccount/")
public class SaleAccountController {
	@Resource
	private SaleAccountService saleAccountService;
	
	@Resource
	private UserAccountService userAccountService;
	
	//注册验证
		@RequestMapping(value="registValidate")
		public ModelAndView registValidate(String username,String password,int sex){
			ModelAndView view = new ModelAndView();
			if(sex == 0){
				//商户注册验证
				SaleAccount saleAccount = new SaleAccount();
				saleAccount.setSaleAccount(username);
				saleAccount.setPassword(password);
				
				int row = saleAccountService.registValidate(saleAccount);
				if(row >0){
					view.addObject("username", username);
//					view.setViewName("index");//回到商城主页面
					view.setViewName("user/login");   //注册成功重新登录
				}else if(row == 0){
					view.addObject("msg", "<script>alert('该账号已存在，请输入其他的账号！')</script>");
					view.setViewName("user/register");//退回注册页面
				}
				
			}else if(sex == 1){
				//用户注册验证
				UserAccount userAccount = new UserAccount();
				userAccount.setUserAccount(username);
				userAccount.setPassword(password);
				
				int row = userAccountService.registValidate(userAccount);
				if(row >0){
					view.addObject("username", username);
//					view.setViewName("index");//回到商城主页面
					view.setViewName("user/login");   //注册成功重新登录
				}else if(row == 0){
					view.addObject("msg", "<script>alert('该账号已存在，请输入其他的账号！')</script>");
					view.setViewName("user/register");//退回注册页面
				}
				
			}
			return view;
			
		}
		
		//商户登录验证
		@RequestMapping(value="loginValidate")
	    public String userLogin(HttpServletRequest request, HttpSession httpSession,ModelMap map,HttpServletResponse response,Model model) {
	        
			//String redirUrl = request.getParameter("redirUrl");
			String redirUrl = request.getHeader("referer");
			if(redirUrl.contains("redirUrl")){
				redirUrl = redirUrl.substring(redirUrl.lastIndexOf("http"));				
			}else{
				redirUrl = null;
			}
			System.out.println("redirUrl:"+redirUrl);
			
			String userName = request.getParameter("username");
	        String loginPwd = request.getParameter("password");
	        int sex = Integer.parseInt(request.getParameter("sex"));//判断是用户登陆还是商户登陆
	        httpSession.setAttribute("sex", sex);
	        //获取随机码
	        //String md5RandomKey = (String)request.getSession().getAttribute("md5RandomKey"); 
	        //用户名存进这个实例中
	        if(sex == 0){
	        	SaleAccount saleAccount = new SaleAccount();
	            saleAccount.setSaleAccount(userName);
	            //查询这个用户名相等的商户
	            SaleAccount sale=saleAccountService.loginVAlidatemd5(saleAccount);
	            if(sale!=null){
	            		String realPasword=sale.getPassword();
		                if(loginPwd.equals(realPasword)){
		                    System.out.println("登录成功");
		                    //登陆成功，获取session
		        			HttpSession session =request.getSession();
		        			SaleAccount saleToken =sale;
		        			session.setAttribute("saleToken",saleToken);
		        			return "index";
		                }else{
		                    model.addAttribute("msg","<script>alert('密码错误，登录失败！')</script>");
		                    return "user/login";
		                }
	        	}else {
	        		//System.out.println("用户名不存在，登录失败");
	        		model.addAttribute("msg","<script>alert('用户名不存在，登录失败！')</script>");
	        		return "user/login";
	        	}
	        }else if(sex == 1){
	        	UserAccount userAccount = new UserAccount();
	        	userAccount.setUserAccount(userName);
	            //查询这个用户名所拥有的密码的值并显示出来进行测试
//	            String realPasword=saleAccountService.loginVAlidatemd5(saleAccount);
	            
	            UserAccount user = userAccountService.loginVAlidatemd5(userAccount);	                        
	            if (user!= null) {
	                if(loginPwd.equals(user.getPassword())){
	                    System.out.println("登录成功");
	                    //登陆成功，存取session
	        			HttpSession session =request.getSession();
	        			UserAccount userToken =user;
	        			session.setAttribute("userToken",userToken);
//	                    return "user/productList";
	        			//return "redirect:/goods/firstQuery";	        			
	        			//多添加的代码
	        			if(redirUrl != null && !redirUrl.equals("")){      				
	        				try {
								response.sendRedirect(redirUrl);
							} catch (IOException e) {
							} 				
	        			}else{
	        				return "redirect:/goods/firstQuery";
	        			}       			
	        			
	                }else{
	                    System.out.println("密码错误，登录失败");
	                    model.addAttribute("msg","<script>alert('密码错误，登录失败！')</script>");
	                    return "user/login";
	                }
	        	}else {
	        		System.out.println("用户名不存在，登录失败");
	        		model.addAttribute("msg","<script>alert('用户名不存在，登录失败！')</script>");
	        		return "user/login";
	        	}
	        }
	        return null;
		}
		
		@RequestMapping(value="logout")
		public String logout(HttpServletRequest request){
			HttpSession session = request.getSession(false);
			if(session == null){
				return "redirect:/goods/firstQuery";
			}
			session.removeAttribute("userToken");
			return "redirect:/goods/firstQuery";
		}
		
		@RequestMapping(value="logout1")
		public String logoutSale(HttpServletRequest request){
			HttpSession session = request.getSession(false);
			if(session == null){
				return "user/login";
			}
			session.removeAttribute("saleToken");
			return "user/login";
		}
		
		/*
		 * 根据session的值获取商户账户名称
		 */
		@RequestMapping(value="/getSaleAccount")
		public ModelAndView getSaleAccount(HttpServletRequest request){
			HttpSession session=request.getSession();	
			SaleAccount sale=(SaleAccount)session.getAttribute("saleToken");
			ModelAndView mView=new ModelAndView();
			String saleAccount=sale.getSaleAccount();
			mView.addObject("saleAccount",saleAccount);
			return mView;
		}
}
